package cn.codeinn.generator.service.impl;

import java.lang.reflect.Field;
import java.util.List;

import javax.persistence.Id;

import org.springframework.beans.factory.annotation.Autowired;

import cn.codeinn.generator.service.IService;
import cn.codeinn.generator.util.BaseMapper;

import cn.vkits.core.collection.CollUtil;
import cn.vkits.core.util.ClassUtil;
import tk.mybatis.mapper.entity.Example;

public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
	@Autowired
	protected M mapper;

	protected static boolean retBool(int result) {
		return result >= 1;
	}

	@Override
	public boolean insert(T entity) {
		return retBool(mapper.insert(entity));
	}

	@Override
	public boolean insertSelective(T entity) {
		return retBool(mapper.insertSelective(entity));
	}

	@Override
	public boolean insertList(List<T> entityList) {
		if (CollUtil.isEmpty(entityList)) {
			throw new IllegalArgumentException("Error: entityList must not be empty");
		}
		return retBool(mapper.insertList(entityList));
	}

	@Override
	public boolean insertUseGeneratedKeys(T entity) {
		return retBool(mapper.insertUseGeneratedKeys(entity));
	}

	@Override
	public boolean deleteByPrimaryKey(Object id) {
		return retBool(mapper.deleteByPrimaryKey(id));
	}

	@Override
	public boolean delete(T entity) {
		return retBool(mapper.delete(entity));
	}

	@Override
	public boolean deleteBatchIds(List<? extends Object> idList) {
		Field[] fields = ClassUtil.getDeclaredFields(ClassUtil.getTypeArgument(getClass(), 1));
		String filedName = "id";
		for (Field field : fields) {
			if (null != field.getAnnotation(Id.class)) {
				filedName = field.getName();
			}
		}
		Example example = new Example(ClassUtil.getTypeArgument(getClass(), 1));
		example.createCriteria().andIn(filedName, idList);
		return retBool(mapper.deleteByExample(example));
	}

	@Override
	public boolean updateByPrimaryKey(T entity) {
		return retBool(mapper.updateByPrimaryKey(entity));
	}

	@Override
	public boolean updateByPrimaryKeySelective(T entity) {
		return retBool(mapper.updateByPrimaryKeySelective(entity));
	}

	@Deprecated
	@Override
	public boolean updateBatchById(List<T> entityList) {
		return false;
	}

	@Deprecated
	@Override
	public boolean updateAllColumnBatchById(List<T> entityList) {
		return false;
	}

	@Override
	public T selectByPrimaryKey(Object id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public List<T> selectAll() {
		return mapper.selectAll();
	}

	@Override
	public Integer selectByMap(T entity) {
		return mapper.selectCount(entity);
	}

	@Override
	public T selectOne(T entity) {
		return mapper.selectOne(entity);
	}
}
